const { User, validateUser } = require('../../model/user');
const bcrypt = require('bcryptjs');
module.exports = async(req, res, next) => {
    //进行新建用户
    //首先验证数据格式
    //验证邮箱是否占用
    //上面都没有就可以进行创建
    const user = req.body;
    const { error } = await validateUser(user);
    if (error) {
        return next(JSON.stringify({ path: '/admin/user-edit', message: error.message }));
    } else {
        const oldUser = await User.findOne({ email: user.email });
        if (oldUser) {
            return next(JSON.stringify({ path: '/admin/user-edit', message: '该邮箱已经被占用' }));
        }
        const salt = await bcrypt.genSalt(10);
        const pass = await bcrypt.hash(user.password, salt);
        user.password = pass;
        await User.create(user);
        res.redirect('/admin/user');
    }
}